<template>
  <div>
    <div style="text-align: left; padding-right: 10px; margin-bottom: 10px">
      <el-input v-model="search" placeholder="请输入搜索关键字" style="width: 20%; margin-right: 10px" clearable></el-input>
      <el-button type="primary" @click="load">搜索</el-button>
      <el-button type="success" @click="add">添加</el-button>
    </div>

    <el-table :data="tableData" stripe style="width: 100%; margin-bottom: 10px;">
      <el-table-column prop="id" label="编号" width="180" sortable />
      <el-table-column prop="studentname" label="学生姓名" width="180" />
      <el-table-column prop="gender" label="性别" />
      <el-table-column prop="age" label="年龄" />
      <el-table-column prop="address" label="家庭地址" />
      <el-table-column fixed="right" label="操作" width="150">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination :current-page="pageNum" :page-count="pages" :total="total"
      layout="total, prev, pager, next, jumper" @current-change="handleCurrentChange" />

    <el-dialog v-model="dialogVisible" title="学生信息" width="30%" destroy-on-close="true">
      <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="demo-ruleForm" status-icon>
        <el-form-item label="学生姓名" prop="studentname">
          <el-input v-model="form.studentname" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio v-model="form.gender" label="男" size="large">男</el-radio>
          <el-radio v-model="form.gender" label="女" size="large">女</el-radio>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="form.age" />
        </el-form-item>
        <el-form-item label="家庭住址" prop="address">
          <el-input type="textarea" v-model="form.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script>


import { onMounted, reactive, toRefs, getCurrentInstance } from "vue"
import axios from "axios"
import { ElMessage, ElMessageBox } from "element-plus"

export default {
    name:"studentView",
    setup() {
    const state = reactive({
      tableData: [],
      pageNum: 1,
      pages: 0,
      total: 0,
      search: "",
      form: {
        id: "",
        studentname: "",
        gender: "男",
        age: 18,
        address: ""
      },
      dialogVisible: false,
      rules: {
        studentname: [
          { required: true, message: '请填写学生姓名', trigger: 'blur' }
        ],
        age: [
          { pattern: /^(1[89]|[2-9][0-9])$/, message: '请输入18-99的年龄', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '请填写家庭地址', trigger: 'blur' }
        ],
      },
    })

    const { proxy } = getCurrentInstance();

    const submitForm = () => {
      proxy.$refs['ruleFormRef'].validate((valid) => {
        if (valid) {
          save()
        } else {
          console.log('请按提示填写');
          return false;
        }
      });
    }

    const resetForm = () => {
      proxy.$refs['ruleFormRef'].resetFields();
    }

    const load = () => {
      axios.get("/api/students", {
        params: {
          pageNum: state.pageNum,
          search: state.search,
        },
      })
        .then((res) => {
          console.log(res);
          state.tableData = res.data.data.records
          state.total = res.data.data.total
          state.pages = res.data.data.pages
        })
    }

    onMounted(() => {
      load()
    })

    const handleCurrentChange = (pageNum) => {
      state.pageNum = pageNum;
      load();
    }

    const add = () => {
      state.dialogVisible = true;
      state.form = {
        gender: "男",
        age: 18,
      }
    }

    const save = () => {
      axios.post("/api/students", state.form).then((res) => {
        if (res.data.code === "0") {
          ElMessage({
            message: "操作成功",
            type: "success",
          })
        } else {
          ElMessage.error(res.msg)
        }
        load()
        state.dialogVisible = false
      });
    }

    const handleEdit = (row) => {
      state.form = row
      state.dialogVisible = true
    }

    const handleDelete = (id) => {
      ElMessageBox.confirm(
        '确认要删除信息吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          axios.delete("/api/students/" + id).then((res) => {
            if (res.data.code === "0") {
              ElMessage({
                message: "删除成功！",
                type: "success",
              })
            } else {
              ElMessage.error(res.msg);
            }
            load();
            state.dialogVisible = false;
          })
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消操作',
          })
        })
    }

    return {
      ...toRefs(state),
      handleCurrentChange,
      add,
      save,
      handleEdit,
      handleDelete,
      load,
      submitForm,
      resetForm,
    }
  }
}
</script>